﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using NormReference.Models;
using NormReference.DAL;
using System.IO;
using System.Diagnostics;

namespace NormReference.Services
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "NormReferenceService" in code, svc and config file together.
    public class NormReferenceService : INormReferenceService
    {
        private NormReferenceContext db = new NormReferenceContext();

        public void NormReference()
        {    
            //Get queue data. 
            Logger.getInstance().printToLogFile("Norm Referencing beginning.  Writing out group dat files. ");
            List<ComparisonGroupQueue_Backup> groupsList = db.comparisonGroupQueue_Backup.ToList();
            Logger.getInstance().printToLogFile("Group List size: " + groupsList.Count);
            
            foreach(ComparisonGroupQueue_Backup backupRow in groupsList)
            {
                //Get group from database. 
                Logger.getInstance().printToLogFile("Back up ID: " + backupRow.ID);
                Logger.getInstance().printToLogFile("Back up: Group ID: " + backupRow.value);
                Logger.getInstance().printToLogFile("Count in Queue: " + db.comparisonGroupQueue_Backup.Count());
                ComparisonGroup groupToNormReference = db.groups.Find(backupRow.value);

                if (groupToNormReference == null)
                {
                    Logger.getInstance().printToLogFile("No group returned.");
                    db.comparisonGroupQueue_Backup.Remove(backupRow);
                }
                else
                {
                    //Write to PVALUES file. 
                    Logger.getInstance().printToLogFile("Looping through queue.");
                    groupToNormReference.generateSQL();
                    FileStream stream = new FileStream("C:\\Program Files\\Maple 14\\bin.win\\SCTL-FILES\\PVALUES.txt", FileMode.Create);
                    StreamWriter groupWriter = new StreamWriter(stream);
                    groupWriter.Write("");
                    groupWriter.Write(groupToNormReference.printProbabilities());
                    groupWriter.Close();
                    Logger.getInstance().printToLogFile("It should be writing this: " + groupToNormReference.printResponseCounts());
                    Logger.getInstance().printToLogFile("Done with group " + groupToNormReference.name);
                    db.comparisonGroupQueue_Backup.Remove(backupRow);


                    //Run Perl Script. 
                    //Logger.getInstance().printToLogFile("Starting Perl Script. ");
                    //Process proc = new Process();
                    //proc.StartInfo.WorkingDirectory = @"C:\WINDOWS\system32";
                    //proc.StartInfo.FileName = @"perl.exe ";
                    //proc.StartInfo.UseShellExecute = false;
                    //proc.StartInfo.RedirectStandardOutput = true;
                    //proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    //proc.StartInfo.CreateNoWindow = true;
                    //proc.StartInfo.RedirectStandardError = true;
                    //proc.StartInfo.RedirectStandardInput = true;
                    //proc.Start();
                    //proc.StandardInput.WriteLine(@"cd C:\Program Files\Maple 14\bin.win\SCTL-FILES");
                    //proc.StandardInput.WriteLine(@"perl SCTL-SCRIPT.pl");
                    //string results = proc.StandardOutput.ReadToEnd();
                    //proc.Close();
                    //proc.WaitForExit();
                    //Logger.getInstance().printToLogFile("CMD results: " + results);

                    
                    //ReadNormReferenceResults(groupToNormReference.ID);
                    //ReportFacultyResults();
                }
                
            }
            db.SaveChanges();   
        }

        public void ReadNormReferenceResults(int comparisonGroupID)
        {
            string path = @"C:\Program Files\Maple 14\bin.win\SCTL-FILES\SCTL-RESULT-FILES\results-sctl.csv";
            List<string[]> results = CSVReader.getInstance().parseCSV(path);

            Logger.getInstance().printToLogFile("Reading CSV File");
            foreach (string[] row in results)
            {
                Logger.getInstance().printToLogFile("Probability: " + row[2]);
                Logger.getInstance().printToLogFile("Value: " + row[3]);
                NormReferenceResult normReferenceResult = new NormReferenceResult();
                normReferenceResult.comparisonGroupID = comparisonGroupID;
                normReferenceResult.questionNumber = row[0];
                normReferenceResult.nsize = row[1];
                normReferenceResult.probability = decimal.Parse(row[2].ToString().Trim(), System.Globalization.NumberStyles.Any);
                normReferenceResult.value = decimal.Parse(row[3].ToString().Trim(), System.Globalization.NumberStyles.Any);
                db.normReferenceResults.Add(normReferenceResult);
                Logger.getInstance().printToLogFile(normReferenceResult.ToString());
            }
            db.SaveChanges();
        }

        public void ClearResults()
        {
            
            
        }

        public void ReportFacultyResults()
        {
            List<FacultyReport> facultyReports = db.FacultyReports.ToList();
            
            foreach (FacultyReport report in facultyReports)
            {
                Logger.getInstance().printToLogFile("Emailing Faculty Report");
                FacultyReportWriter.getInstance().EmailReport(3.66m, "N6", report);
            }
        }
    }
}
